<template>
  <div class="home-view-content">
    <div class="top-bar">
      <button @click="previousDay" class="nav-button">&#xE72B;</button>
      <h2 class="current-date">{{ formattedDisplayDate }}</h2>
      <button @click="nextDay" class="nav-button">&#xE72A;</button>
      <button @click="goToToday" class="today-button">回到今日</button>
    </div>

    <div class="add-todo-section">
      <input 
        type="text" 
        class="todo-input" 
        placeholder="添加新的待办事项..." 
        v-model="newTodoText" 
        @keyup.enter="handleAddTodo"
      >
      <button @click="handleAddTodo" class="add-button">添加</button>
    </div>

    <div class="search-section">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索今日待办..." 
        class="search-input"
      >
    </div>

    <!-- New combined bar -->
    <div class="actions-and-filters-bar">
      <div class="batch-actions-area" v-if="searchedTodos.length > 0">
        <input 
          type="checkbox" 
          :checked="isAllSelected && searchedTodos.length > 0"
          @change="toggleSelectAll"
          id="select-all-todos-today"
          title="全选/取消全选"
          class="select-all-checkbox-today"
        >
        <label for="select-all-todos-today" class="select-all-label-today">全选</label>
        <button @click="handleBatchDeleteToday" :disabled="!hasSelectedTodos" class="batch-action-button delete">
          <span class="button-icon">&#xE74D;</span> 删除选中
        </button>
        <button @click="handleBatchArchiveToday" :disabled="!hasSelectedTodos" class="batch-action-button archive">
          <span class="button-icon">&#xE7B8;</span> 归档选中
        </button>
      </div>
      <div v-else class="batch-actions-area-placeholder">
        <!-- Placeholder to maintain layout structure if needed, or can be empty -->
      </div>

      <div class="home-filter-controls-container">
        <div class="filter-group">
          <span class="filter-label">状态:</span>
          <button @click="setFilterStatus('all')" :class="{ 'active': filterStatus === 'all' }">全部</button>
          <button @click="setFilterStatus('active')" :class="{ 'active': filterStatus === 'active' }">未完成</button>
          <button @click="setFilterStatus('completed')" :class="{ 'active': filterStatus === 'completed' }">已完成</button>
        </div>
        <div class="filter-group">
          <span class="filter-label">优先级:</span>
          <button @click="setFilterPriority('all')" :class="{ 'active': filterPriority === 'all' }">全部</button>
          <button @click="setFilterPriority(PRIORITIES.HIGH)" :class="{ 'active': filterPriority === PRIORITIES.HIGH }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span>{{ getPriorityText(PRIORITIES.HIGH) }}
          </button>
          <button @click="setFilterPriority(PRIORITIES.MEDIUM)" :class="{ 'active': filterPriority === PRIORITIES.MEDIUM }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span>{{ getPriorityText(PRIORITIES.MEDIUM) }}
          </button>
          <button @click="setFilterPriority(PRIORITIES.LOW)" :class="{ 'active': filterPriority === PRIORITIES.LOW }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span>{{ getPriorityText(PRIORITIES.LOW) }}
          </button>
          <button @click="setFilterPriority(PRIORITIES.NONE)" :class="{ 'active': filterPriority === PRIORITIES.NONE }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span>{{ getPriorityText(PRIORITIES.NONE) }}
          </button>
        </div>
      </div>
    </div>

    <div class="todo-list-section">
      <ul class="todo-list" v-if="paginatedTodos.length > 0">
        <li 
          v-for="todo in paginatedTodos" 
          :key="todo.id" 
          :class="['todo-item', { 'completed': todo.completed, 'selected-for-batch': selectedTodoIds.includes(todo.id) }]"
          @contextmenu.prevent="openContextMenu(todo, $event)"
        >
          <input 
            type="checkbox" 
            :id="'select-todo-today-' + todo.id" 
            class="todo-select-checkbox-today" 
            :checked="selectedTodoIds.includes(todo.id)" 
            @change="toggleTodoSelection(todo.id)"
          >
          <span 
            @click="toggleTodoStatus(todo.id)" 
            :class="['todo-status-icon', todo.completed ? 'completed-icon' : 'pending-icon']"
            :title="todo.completed ? '标记为未完成' : '标记为已完成'"
          >
             {{ todo.completed ? '&#xE930;' : '&#xE931;' }}
          </span>
          <span 
            class="priority-indicator"
            :style="{ backgroundColor: getPriorityColor(todo.priority) }"
            :title="'优先级: ' + getPriorityText(todo.priority)"
          ></span>
          <label 
            v-if="editingTodoId !== todo.id" 
            class="todo-label" 
            @dblclick="startEditing(todo)"
            :title="todo.text"
          >
            {{ todo.text }}
          </label>
          <input 
            v-else 
            type="text" 
            v-model="editingTodoText" 
            class="todo-edit-input" 
            @blur="saveEdit(todo.id)" 
            @keyup.enter="saveEdit(todo.id)" 
            @keyup.esc="cancelEdit"
            v-focus
          />
        </li>
      </ul>
      <div v-else class="empty-list-messages">
        <p v-if="todos.length === 0 && !searchQuery" class="empty-list-message">今天还没有待办事项，快来添加吧！</p>
        <p v-else-if="searchedTodos.length === 0 && searchQuery" class="empty-list-message">没有找到与 "{{ searchQuery }}" 匹配的待办事项。</p>
      </div>
    </div>

    <div class="pagination-controls" v-if="totalPages > 1">
      <button @click="prevPage" :disabled="currentPage === 1" class="pagination-button">上一页</button>
      <span class="pagination-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-button">下一页</button>
    </div>

    <div class="bottom-bar">
      <span class="status-text">
        <template v-if="searchedTodos.length > 0">
          选中 {{ selectedTodoIds.length }} / {{ searchedTodos.length }} 个。
        </template>
        共 {{ searchedTodos.length }} 个匹配任务 (本日总计 {{ todos.length }} 条)，{{ completedSearchedTodosCount }} 个已完成
      </span>
      <div class="priority-legend-container">
        <div class="priority-legend">
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span>
            <span>{{ getPriorityText(PRIORITIES.HIGH) }}</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span>
            <span>{{ getPriorityText(PRIORITIES.MEDIUM) }}</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span>
            <span>{{ getPriorityText(PRIORITIES.LOW) }}</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span>
            <span>{{ getPriorityText(PRIORITIES.NONE) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Context Menu -->
    <div 
      v-if="contextMenu.visible"
      ref="contextMenuRef"
      class="context-menu"
      :style="{ top: contextMenu.top + 'px', left: contextMenu.left + 'px' }"
      @click.stop
      v-click-outside="closeContextMenu"
    >
      <div 
        class="context-menu-item priority-submenu-container"
        ref="prioritySubmenuParentRef"
        @mouseenter="openPrioritySubmenu"
        @mouseleave="scheduleClosePrioritySubmenu"
      >
        <span>设置优先级</span>
        <span class="submenu-arrow">&#xE76C;</span>
      </div>
      <div class="context-menu-item" @click="startEditingContextTodo">编辑</div>
      <div class="context-menu-item" @click="archiveContextTodo">归档</div>
      <div class="context-menu-item" @click="deleteContextTodo">删除</div>
      <div class="context-menu-item" @click="openDatePickerContextTodo">修改日期</div>
    </div>

    <!-- Priority Submenu (moved to be a direct child for easier positioning) -->
    <div
      v-if="prioritySubmenu.visible"
      ref="prioritySubmenuRef"
      class="priority-submenu" 
      :class="{ 'submenu-positioned-left': prioritySubmenu.isPositionedLeft }"
      :style="prioritySubmenu.style"
      @mouseenter="clearClosePrioritySubmenuTimer"
      @mouseleave="scheduleClosePrioritySubmenu(true)"
      @click.stop 
    >
          <div class="context-menu-item" @click="setContextMenuTodoPriority(PRIORITIES.HIGH)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span> 高
          </div>
          <div class="context-menu-item" @click="setContextMenuTodoPriority(PRIORITIES.MEDIUM)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span> 中
          </div>
          <div class="context-menu-item" @click="setContextMenuTodoPriority(PRIORITIES.LOW)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span> 低
          </div>
          <div class="context-menu-item" @click="setContextMenuTodoPriority(PRIORITIES.NONE)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span> {{ getPriorityText(PRIORITIES.NONE) }}
          </div>
    </div>

    <!-- Mini Calendar for Date Picking -->
    <MiniCalendar
      ref="homeMiniCalendar" 
      :initialDate="datePickerInitialDate"
      @date-selected="handleDateSelectedForTodo"
      @close="closeDatePicker"
    />
  </div>
</template>

<script>
import { mapGetters, mapActions, mapState } from 'vuex';
import Vue from 'vue';
import { getPriorityText, getPriorityColor, getPriorityIcon, PRIORITIES } from '../utils/priorityUtils';
import { calculateContextMenuPosition, calculateSubmenuPosition } from '../utils/contextMenuUtils';
import MiniCalendar from '../components/MiniCalendar.vue';
import { getFormattedDateKey as utilGetFormattedDateKey } from '../utils/dateUtils';

// Add a simple click-outside directive
Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = function (event) {
      if (!(el == event.target || el.contains(event.target))) {
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent);
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.clickOutsideEvent);
  },
});

export default {
  name: 'HomeView',
  components: {
    MiniCalendar
  },
  data() {
    return {
      newTodoText: '',
      editingTodoId: null,
      editingTodoText: '',
      selectedTodoIds: [],
      showPriorityMenuForTodoId: null,
      priorityMenuPosition: { top: '0px', left: '0px' },
      contextMenu: {
        visible: false,
        top: 0,
        left: 0,
        selectedTodo: null,
        dimensions: { width: 160, height: 160 },
        isPushedLeft: false
      },
      prioritySubmenu: {
        visible: false,
        style: {},
        isPositionedLeft: false,
        dimensions: { width: 100, height: 130 },
        closeTimer: null
      },
      PRIORITIES: PRIORITIES,
      datePickerTargetTodoId: null,
      datePickerInitialDate: new Date(),
      searchQuery: '',
      currentPage: 1,
      itemsPerPage: 10, // 可以根据需要调整每页的项目数
      filterStatus: 'all', // 'all', 'active', 'completed'
      filterPriority: 'all', // 'all', PRIORITIES.HIGH, etc.
    };
  },
  computed: {
    ...mapState([
      'currentDate'
    ]),
    ...mapGetters([
      'todosForCurrentDate',
      'formattedCurrentDateKey',
      'currentDateObject',
      'isDataReady'
    ]),
    todos() {
      const data = this.todosForCurrentDate;
      // console.log(`[HomeView.vue] Computed 'todos' for ${this.formattedCurrentDateKey}: Count = ${data.length}`);
      return data;
    },
    searchedTodos() {
      let filtered = this.todos;

      // 1. Filter by search query
      if (this.searchQuery) {
        filtered = filtered.filter(todo =>
          todo.text.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }

      // 2. Filter by status
      if (this.filterStatus === 'active') {
        filtered = filtered.filter(todo => !todo.completed);
      } else if (this.filterStatus === 'completed') {
        filtered = filtered.filter(todo => todo.completed);
      }

      // 3. Filter by priority
      if (this.filterPriority !== 'all') {
        filtered = filtered.filter(todo => todo.priority === this.filterPriority);
      }
      
      return filtered;
    },
    totalPages() {
      return Math.ceil(this.searchedTodos.length / this.itemsPerPage);
    },
    paginatedTodos() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = startIndex + this.itemsPerPage;
      return this.searchedTodos.slice(startIndex, endIndex);
    },
    isAllSelected() {
      if (this.paginatedTodos.length === 0) { // Check against current page items
        return false;
      }
      // Check if all items on the current page are selected
      const currentPageItemIds = this.paginatedTodos.map(t => t.id);
      return currentPageItemIds.every(id => this.selectedTodoIds.includes(id));
    },
    hasSelectedTodos() {
      return this.selectedTodoIds.length > 0;
    },
    formattedDisplayDate() {
      if (!this.currentDateObject) return '加载中...';
      return this.currentDateObject.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
    },
    completedTodosCount() {
      return this.todos.filter(todo => todo.completed).length;
    },
    completedSearchedTodosCount() {
      return this.searchedTodos.filter(todo => todo.completed).length;
    },
    getFormattedDateKey() {
      return utilGetFormattedDateKey;
    }
  },
  methods: {
    ...mapActions([
      'selectDate',
      'nextDay',
      'previousDay',
      'goToToday',
      'addTodo',
      'toggleTodo',
      'updateTodoText',
      'deleteTodo',
      'archiveTodo',
      'archiveTodoFromDate',
      'deleteBatchTodosFromDate',
      'archiveBatchTodos',
      'updateTodoPriority',
      'moveTodoToDate',
      'setSelectedDate',
      'fetchTodosForDate'
    ]),
    getPriorityText,
    getPriorityColor,
    getPriorityIcon,
    handleAddTodo() {
      if (this.newTodoText.trim()) {
        console.log(`[HomeView] handleAddTodo: Adding new todo with text: "${this.newTodoText.trim()}" for dateKey: ${this.formattedCurrentDateKey}`);
        this.addTodo(this.newTodoText.trim());
        this.newTodoText = '';
      }
    },
    toggleTodoStatus(todoId) {
      console.log(`[HomeView] toggleTodoStatus: Toggling todo with id: ${todoId} on dateKey: ${this.formattedCurrentDateKey}`);
      this.toggleTodo(todoId);
    },
    handleDeleteTodo(todoId) {
      console.log(`[HomeView] handleDeleteTodo: Deleting todo with id: ${todoId} from dateKey: ${this.formattedCurrentDateKey}`);
      this.deleteTodo({ todoId, dateKey: this.formattedCurrentDateKey });
    },
    handleArchiveTodo(todoId) {
      console.log(`[HomeView] handleArchiveTodo: Archiving todo with id: ${todoId} from dateKey: ${this.formattedCurrentDateKey}`);
      this.archiveTodoFromDate({ todoId, dateKey: this.formattedCurrentDateKey });
    },
    toggleSelectAll() {
      const currentPageItemIds = this.paginatedTodos.map(t => t.id);
      if (this.isAllSelected) {
        // Unselect all items on the current page
        this.selectedTodoIds = this.selectedTodoIds.filter(id => !currentPageItemIds.includes(id));
      } else {
        // Select all items on the current page, ensuring no duplicates
        const newSelectedIds = new Set([...this.selectedTodoIds, ...currentPageItemIds]);
        this.selectedTodoIds = Array.from(newSelectedIds);
      }
      console.log("[HomeView] toggleSelectAll: Selected IDs:", this.selectedTodoIds);
    },
    toggleTodoSelection(todoId) {
      const index = this.selectedTodoIds.indexOf(todoId);
      if (index > -1) {
        this.selectedTodoIds.splice(index, 1);
      } else {
        this.selectedTodoIds.push(todoId);
      }
      console.log("[HomeView] toggleTodoSelection: Selected IDs:", this.selectedTodoIds);
    },
    handleBatchDeleteToday() {
      if (this.selectedTodoIds.length > 0) {
        console.log("[HomeView] handleBatchDeleteToday: Deleting todos:", this.selectedTodoIds, "from dateKey:", this.formattedCurrentDateKey);
        this.deleteBatchTodosFromDate({ dateKey: this.formattedCurrentDateKey, todoIdsArray: [...this.selectedTodoIds] });
        this.selectedTodoIds = [];
      }
    },
    handleBatchArchiveToday() {
      if (this.hasSelectedTodos) {
        console.log(`[HomeView] handleBatchArchiveToday: Archiving todos:`, this.selectedTodoIds, `from dateKey:`, this.formattedCurrentDateKey);
        this.archiveBatchTodos({
          todoIds: [...this.selectedTodoIds],
          source: 'date',
          dateKeyIfFromDate: this.formattedCurrentDateKey
        });
        this.selectedTodoIds = [];
      }
    },
    startEditing(todo) {
      this.editingTodoId = todo.id;
      this.editingTodoText = todo.text;
      console.log(`[HomeView] startEditing: Started editing todo id: ${todo.id}, current text: "${todo.text}"`);
    },
    saveEdit(todoId) {
      if (this.editingTodoId === todoId && this.editingTodoText.trim()) {
        console.log(`[HomeView] saveEdit: Saving edit for todo id: ${todoId}, new text: "${this.editingTodoText.trim()}" for dateKey: ${this.formattedCurrentDateKey}`);
        this.updateTodoText({ todoId, newText: this.editingTodoText.trim(), dateKey: this.formattedCurrentDateKey });
      }
      this.cancelEdit();
    },
    cancelEdit() {
      console.log(`[HomeView] cancelEdit: Cancelling edit for todo id: ${this.editingTodoId}`);
      this.editingTodoId = null;
      this.editingTodoText = '';
    },
    openContextMenu(todo, event) {
      this.contextMenu.selectedTodo = todo;
      const { top, left, adjustedLeft } = calculateContextMenuPosition(event, this.contextMenu.dimensions);
      this.contextMenu.top = top;
      this.contextMenu.left = left;
      this.contextMenu.isPushedLeft = adjustedLeft; 
      this.contextMenu.visible = true;
      console.log(`[HomeView] openContextMenu: Opened for todo id: ${todo.id} at (${left}px, ${top}px). Pushed left: ${adjustedLeft}`);

      if (this.prioritySubmenu.visible) {
        this.prioritySubmenu.visible = false;
      }
    },
    closeContextMenu() {
      if (this.contextMenu.visible) {
        console.log("[HomeView] closeContextMenu: Closing main context menu.");
      this.contextMenu.visible = false;
      this.contextMenu.selectedTodo = null;
        if (this.prioritySubmenu.visible) {
          this.prioritySubmenu.visible = false;
        }
      }
    },
    openPrioritySubmenu() {
      if (!this.$refs.prioritySubmenuParentRef) return;
      this.clearClosePrioritySubmenuTimer();

      this.prioritySubmenu.visible = true;

      this.$nextTick(() => {
        if (!this.$refs.prioritySubmenuParentRef || !this.$refs.prioritySubmenuRef) {
          this.prioritySubmenu.visible = false;
          return;
        }
        const parentRect = this.$refs.prioritySubmenuParentRef.getBoundingClientRect();
        
        const submenuDimensions = this.prioritySubmenu.dimensions;

        const { top, left, positionedRight } = calculateSubmenuPosition(parentRect, submenuDimensions);
        
        this.prioritySubmenu.style = {
          top: `${top}px`,
          left: `${left}px`,
        };
        this.prioritySubmenu.isPositionedLeft = !positionedRight;
        console.log(`[HomeView] openPrioritySubmenu: Submenu at T:${top}, L:${left}. Positioned Right: ${positionedRight}`);
      });
    },
    scheduleClosePrioritySubmenu(isMouseLeaveFromSubmenu = false) {
      this.clearClosePrioritySubmenuTimer();
      this.prioritySubmenu.closeTimer = setTimeout(() => {
        this.prioritySubmenu.visible = false;
        console.log("[HomeView] scheduleClosePrioritySubmenu: Submenu closed via timer.");
      }, isMouseLeaveFromSubmenu ? 50 : 150);
    },
    clearClosePrioritySubmenuTimer() {
      if (this.prioritySubmenu.closeTimer) {
        clearTimeout(this.prioritySubmenu.closeTimer);
        this.prioritySubmenu.closeTimer = null;
      }
    },
    setContextMenuTodoPriority(priority) {
      if (this.contextMenu.selectedTodo) {
        this.updateTodoPriority({ todoId: this.contextMenu.selectedTodo.id, priority, dateKey: this.formattedCurrentDateKey });
      }
      this.closeContextMenu();
    },
    startEditingContextTodo() {
      if (this.contextMenu.selectedTodo) {
        this.startEditing(this.contextMenu.selectedTodo);
      }
      this.closeContextMenu();
    },
    archiveContextTodo() {
      if (this.contextMenu.selectedTodo) {
        console.log(`[HomeView] archiveContextTodo: Archiving todo id ${this.contextMenu.selectedTodo.id} from dateKey ${this.formattedCurrentDateKey}`);
        this.archiveTodoFromDate({ todoId: this.contextMenu.selectedTodo.id, dateKey: this.formattedCurrentDateKey });
      }
      this.closeContextMenu();
    },
    deleteContextTodo() {
      if (this.contextMenu.selectedTodo && this.contextMenu.selectedTodo.id) {
        console.log(`[HomeView] deleteContextTodo: Deleting todo with id: ${this.contextMenu.selectedTodo.id}`);
        this.deleteTodo({ todoId: this.contextMenu.selectedTodo.id, dateKey: this.formattedCurrentDateKey });
      } else {
        console.warn("[HomeView] deleteContextTodo: Attempted to delete with no selected todo or no todo id.", this.contextMenu.selectedTodo);
      }
      this.closeContextMenu();
    },
    openDatePickerContextTodo() {
      if (this.contextMenu.selectedTodo) {
        const todo = this.contextMenu.selectedTodo;
        const eventTargetElement = this.$refs.contextMenuRef;
        this.datePickerTargetTodoId = todo.id;
        this.datePickerInitialDate = todo.date ? new Date(todo.date) : new Date(this.currentDateObject);

        if (this.$refs.homeMiniCalendar) {
            this.$refs.homeMiniCalendar.open(eventTargetElement);
        }
      }
      this.closeContextMenu();
    },
    closeDatePicker() {
      console.log("[HomeView] closeDatePicker: Closing date picker.");
      this.datePickerTargetTodoId = null;
    },
    handleDateSelectedForTodo(selectedDate) {
      if (this.datePickerTargetTodoId) {
        const originalDateKey = this.formattedCurrentDateKey;
        console.log(`[HomeView] handleDateSelectedForTodo: Attempting to move todoId: ${this.datePickerTargetTodoId} from originalDateKey: ${originalDateKey} to new date:`, selectedDate);
        const todoToMove = this.todosForCurrentDate.find(t => t.id === this.datePickerTargetTodoId);
        console.log(`[HomeView] Found todo in todosForCurrentDate:`, JSON.parse(JSON.stringify(todoToMove)));
        this.moveTodoToDate({ todoId: this.datePickerTargetTodoId, originalDateKey, newDate: selectedDate });
        console.log(`[HomeView] moveTodoToDate action called for todoId: ${this.datePickerTargetTodoId}`);
        this.datePickerTargetTodoId = null;
      }
    },
    // Pagination methods
    goToPage(pageNumber) {
      if (pageNumber >= 1 && pageNumber <= this.totalPages) {
        this.currentPage = pageNumber;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    // Filter methods
    setFilterStatus(status) {
      this.filterStatus = status;
    },
    setFilterPriority(priority) {
      this.filterPriority = priority;
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.focus();
      },
      update: function(el, binding, vnode) {
        if (vnode.key === vnode.context.editingTodoId) {
             Vue.nextTick(() => el.focus());
        }
      }
    }
  },
  watch: {
    currentDate(newDate, oldDate) {
      console.log(`[HomeView.vue] Watcher: Vuex state.currentDate changed from ${oldDate ? oldDate.toISOString() : 'null'} to ${newDate ? newDate.toISOString() : 'null'}`);
      this.selectedTodoIds = [];
      this.currentPage = 1; // Reset page when date changes
      this.searchQuery = ''; // Optionally reset search query on date change
    },
    formattedCurrentDateKey: {
      handler(newDateKey, oldDateKey) {
        if (newDateKey && newDateKey !== oldDateKey) {
          console.log(`[HomeView.vue] Watcher: formattedCurrentDateKey changed to ${newDateKey}. Fetching todos.`);
          this.fetchTodosForDate(newDateKey);
          this.currentPage = 1; // Reset page as data for a new date is fetched
          // searchQuery might persist or be cleared based on desired UX
        }
      },
      immediate: false
    },
    todosForCurrentDate: { // This watcher might be redundant if `formattedCurrentDateKey` handles it
      handler(newTodos, oldTodos) {
        // Reset current page if the underlying list of todos changes significantly
        // this.currentPage = 1; // Be careful, this might reset too often.
        // The totalPages watcher should handle out-of-bounds currentPage.
        if (newTodos.length > 0) {
        }
      },
      deep: true,
    },
    searchQuery() {
      this.currentPage = 1; // Reset to first page when search query changes
    },
    totalPages(newTotalPages) {
      if (this.currentPage > newTotalPages && newTotalPages > 0) {
        this.currentPage = newTotalPages; // Adjust if current page is out of bounds
      } else if (newTotalPages === 0) {
        this.currentPage = 1; // Or handle as no pages (e.g. disable pagination)
      }
    },
    filterStatus() {
      this.currentPage = 1;
    },
    filterPriority() {
      this.currentPage = 1;
    },
    isDataReady(newValue) {
        console.log(`[HomeView.vue] Watcher: isDataReady (getter) changed to: ${newValue}`);
        if(newValue) {
        }
    }
  },
  created() {
  },
  mounted() {
    console.log("[HomeView.vue] Component mounted. Current dateKey for initial fetch:", this.formattedCurrentDateKey);
    if (this.formattedCurrentDateKey) {
      this.fetchTodosForDate(this.formattedCurrentDateKey);
    } else {
      console.warn("[HomeView.vue] formattedCurrentDateKey is not available on mount. Initial fetch might be delayed.");
      if (this.currentDateObject) {
        const initialKey = this.getFormattedDateKey(this.currentDateObject);
        if (initialKey) {
          console.log("[HomeView.vue] Fallback: Fetching for initialKey derived from currentDateObject:", initialKey);
          this.fetchTodosForDate(initialKey);
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* Removed: @import '@/assets/scss/variables'; as variables are now global CSS vars */

.home-view-content {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--theme-bg-content-area);
  color: var(--theme-text-primary);
  gap: 0; /* Reset gap, individual sections will manage their padding/margins */
}

.top-bar {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-base);
  background: var(--theme-bg-titlebar); /* Use titlebar background */
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
}

  .current-date {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--theme-text-primary);
  margin: 0 var(--spacing-base);
    text-align: center;
  flex-grow: 1;
  }

.nav-button, .today-button {
  background: transparent;
  border: var(--border-width) var(--border-style) transparent;
  color: var(--theme-text-secondary);
  padding: var(--spacing-xs) var(--spacing-sm);
  font-family: var(--font-family-icons);
  font-size: var(--font-size-lg);
  border-radius: var(--border-radius-base);
    cursor: pointer;
  transition: all var(--transition-duration-short);
  }
  .today-button {
  font-family: var(--font-family-base);
  font-size: var(--font-size-sm);
  margin-left: var(--spacing-base);
}

.nav-button:hover, .today-button:hover {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-secondary);
}

.add-todo-section {
  display: flex;
  align-items: center;
  padding: var(--spacing-base);
  gap: var(--spacing-md);
  background: var(--theme-bg-secondary); /* Use secondary for this distinct section */
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
}

  .todo-input {
    flex-grow: 1;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
}
.todo-input::placeholder {
  color: var(--theme-text-muted);
  opacity: 1; /* Ensure placeholder opacity is not double-applied */
}
.todo-input:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
  }

  .add-button {
  padding: var(--spacing-sm) var(--spacing-lg);
  background: var(--theme-accent-gradient);
  color: var(--theme-text-on-accent);
    border: none;
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
    cursor: pointer;
  transition: filter var(--transition-duration-short), box-shadow var(--transition-duration-short);
  white-space: nowrap;
}
.add-button:hover {
  filter: brightness(1.1);
  box-shadow: 0 2px 8px rgba(var(--theme-accent-primary-rgb), 0.2);
    }
.add-button:active {
  filter: brightness(0.95);
}

.search-section {
  padding: var(--spacing-base);
  background: var(--theme-bg-secondary); /* Match add-todo section or distinct */
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
}

.search-input {
  width: 100%; /* Take full width */
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
}
.search-input::placeholder {
  color: var(--theme-text-muted);
}
.search-input:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

/* Styles for the new combined actions and filters bar */
.actions-and-filters-bar {
  display: flex;
  justify-content: space-between; 
  align-items: center; 
  padding: var(--spacing-sm) var(--spacing-base);
  background-color: var(--theme-bg-secondary);
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
  gap: var(--spacing-md);
  flex-wrap: nowrap;
}

.batch-actions-area {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.batch-actions-area-placeholder {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

/* REMOVED .filters-area styles */

/* ADDED styles for the new container, mimicking .filter-sort-controls from CollectionBoxView */
.home-filter-controls-container {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.filter-group {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.filter-label {
  font-size: var(--font-size-sm);
  color: var(--theme-text-secondary);
  margin-right: var(--spacing-xs);
  font-weight: var(--font-weight-medium);
}

.filter-group button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.filter-group button:hover {
  border-color: var(--theme-accent-primary);
  color: var(--theme-accent-primary);
}

.filter-group button.active {
  background: var(--theme-accent-gradient);
  color: var(--theme-text-on-accent);
  border-color: transparent;
  font-weight: var(--font-weight-medium);
}
.filter-group button.active .priority-dot-filter {
  /* Ensure dot is visible on active button if its color clashes */
   border: 1px solid rgba(0,0,0,0.1); /* Example, adjust as needed */
}


.priority-dot-filter {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
  /* display: inline-block; */ /* if not using flex on button */
}

.todo-list-section {
  flex-grow: 1;
  overflow-y: auto;
  padding: var(--spacing-base);
  background-color: var(--theme-bg-content-area); /* Ensure content area bg is used */
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

  .todo-item {
    display: flex;
    align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-card);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
  gap: var(--spacing-md);
  /* Removed position: relative and distinct border-bottom as border is now all-around */
}
/* .todo-item:last-child { border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary); } Removed as border is now all-around */
.todo-item:hover {
  border-color: var(--theme-border-secondary); /* Or theme-accent-primary for more highlight */
  background-color: var(--theme-bg-hover);
      }
.todo-item.selected-for-batch {
  background-color: color-mix(in srgb, var(--theme-accent-primary) 20%, var(--theme-bg-card));
  border-color: var(--theme-accent-primary);
    }

    .todo-status-icon {
  font-family: var(--font-family-icons);
  font-size: var(--font-size-lg);
      cursor: pointer;
  color: var(--theme-text-secondary);
  transition: color var(--transition-duration-short);
  padding: var(--spacing-xs);
  border-radius: var(--border-radius-circle);
  line-height: 1;
}
.todo-status-icon:hover {
  color: var(--theme-text-primary);
  background-color: var(--theme-bg-hover);
      }
.todo-status-icon.completed-icon {
  color: var(--theme-accent-primary);
}
.todo-status-icon.completed-icon:hover {
  color: var(--theme-accent-highlight);
    }

    .priority-indicator {
      width: 10px;
      height: 10px;
  border-radius: var(--border-radius-circle);
      flex-shrink: 0;
    }

    .todo-label {
      flex-grow: 1;
  color: var(--theme-text-primary);
  cursor: text;
  user-select: text;
  padding: var(--spacing-xs) 0;
  line-height: var(--line-height-base);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
      min-width: 0;
    }
.todo-item.completed .todo-label {
  color: var(--theme-text-muted);
  text-decoration: line-through;
  text-decoration-color: var(--theme-text-disabled);
}
    
    .todo-edit-input {
      flex-grow: 1;
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  line-height: var(--line-height-base);
  min-width: 0;
}
.todo-edit-input:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.empty-list-messages { /* Container for multiple empty messages */
  text-align: center;
  padding: var(--spacing-xl) var(--spacing-base);
  color: var(--theme-text-muted);
  font-style: italic;
  margin-top: var(--spacing-lg);
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: var(--spacing-base) 0;
  gap: var(--spacing-md);
  flex-shrink: 0;
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  background-color: var(--theme-bg-secondary); /* Or content area background */
}

.pagination-button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
}
.pagination-button:hover:not(:disabled) {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-primary);
}
.pagination-button:disabled {
  color: var(--theme-text-disabled);
  background-color: color-mix(in srgb, var(--theme-bg-button-secondary) 50%, transparent);
  border-color: var(--theme-border-primary);
  cursor: not-allowed;
}
.pagination-info {
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}

.bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-base);
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  background-color: var(--theme-bg-secondary);
  flex-shrink: 0;
}

.status-text {
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}

.priority-legend-container {
  padding: 0;
  background-color: transparent;
}
.priority-legend {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: var(--spacing-md);
}
.legend-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
  }
.legend-dot {
    width: 10px;
    height: 10px;
  border-radius: var(--border-radius-circle);
  }

/* Context Menu & Submenu Styles */
.context-menu, .priority-submenu {
  position: fixed;
  z-index: 1000;
  background-color: var(--theme-bg-tertiary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  box-shadow: 0 4px 12px rgba(var(--theme-shadow-color-rgb, var(--d-shadow-color-rgb)), var(--theme-shadow-opacity-strong, var(--d-shadow-opacity-strong)));
  padding: var(--spacing-xs) 0;
}
.priority-submenu { z-index: 1001; min-width: 100px; }
.context-menu { min-width: 160px; }

.context-menu-item {
  display: flex; align-items: center; gap: var(--spacing-sm);
  padding: var(--spacing-xs) var(--spacing-sm);
  color: var(--theme-text-secondary);
  cursor: pointer; font-size: var(--font-size-sm);
  border: none; background-color: transparent;
  width: 100%; text-align: left;
  transition: background-color var(--transition-duration-short), color var(--transition-duration-short);
}
.context-menu-item:hover {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
}
.context-menu-item .priority-dot {
  width: 10px; height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
}
.priority-submenu-container { position: relative; }
.submenu-arrow {
  font-family: var(--font-family-icons);
  margin-left: auto;
  font-size: calc(var(--font-size-sm) * 0.9);
}

/* Restore batch control styles that might have been removed */
.select-all-checkbox-today {
  appearance: none; -webkit-appearance: none; width: 18px; height: 18px;
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-sm); background-color: var(--theme-bg-input);
  cursor: pointer; position: relative; flex-shrink: 0;
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
}
.select-all-checkbox-today:checked {
  background: var(--theme-accent-primary); border-color: transparent;
}
.select-all-checkbox-today:checked::after {
  content: ''; position: absolute; left: 6px; top: 3px; width: 5px; height: 10px;
  border: solid var(--theme-text-on-accent); border-width: 0 2px 2px 0; transform: rotate(45deg);
}
.select-all-checkbox-today:focus {
  outline: none; box-shadow: 0 0 0 2px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.select-all-label-today {
  color: var(--theme-text-secondary);
  cursor: pointer;
  font-size: var(--font-size-sm);
  user-select: none;
}

.batch-action-button {
  padding: var(--spacing-xs) var(--spacing-sm); font-size: var(--font-size-sm);
  color: var(--theme-text-secondary); background-color: var(--theme-bg-button-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base); cursor: pointer;
  transition: all var(--transition-duration-short); display: flex; align-items: center; gap: var(--spacing-xs);
}
.batch-action-button .button-icon {
  font-family: var(--font-family-icons); font-size: var(--font-size-base);
}
.batch-action-button:hover:not(:disabled) {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-primary);
}
.batch-action-button:disabled {
  color: var(--theme-text-disabled);
  background-color: color-mix(in srgb, var(--theme-bg-button-secondary) 50%, transparent);
  border-color: var(--theme-border-primary);
  cursor: not-allowed;
}
.batch-action-button.delete:hover:not(:disabled) {
  background-color: #B91C1C; /* Specific danger color */
  color: var(--theme-text-on-accent);
  border-color: #991B1B; /* Darker shade for border */
}
.batch-action-button.archive:hover:not(:disabled) {
  background-color: #5856d6; /* Specific archive color */
  color: var(--theme-text-on-accent); 
  border-color: #403fa6; /* Darker shade for border */
}

/* Comment out or remove old individual bar styles if they are fully replaced */
/*
.filter-controls-section { ... }
*/
</style> 